package cn.vcjf.weapp.api.user.service.impl;

import cn.vcjf.weapp.api.user.entity.User;
import cn.vcjf.weapp.api.user.mapper.UserMapper;
import cn.vcjf.weapp.api.user.service.UserService;
import cn.vcjf.weapp.common.util.JWT;
import cn.vcjf.weapp.common.web.TableResult;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhengzihang
 * @since 2018-09-25
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
	@Override
	public User getUserByOpenId(String openId,Integer sysUserId) {
		return baseMapper.getUserByOpenId(openId,sysUserId);
	}

	@Override
	@Transactional(readOnly = false)
	public TableResult getTokenByOpenId(String openId, User userInfo) {
		TableResult result = TableResult.OKResult();
		try {
			//先到数据库验证
			User user = baseMapper.getUserByOpenId(openId,userInfo.getSysUserId());
			//非第一次登录
			JSONObject jsonObject = new JSONObject();
			if (null != user) {
				//已绑定
				if (StringUtils.isNotBlank(user.getPhone())) {
					jsonObject.put("isBind", true);
				} else {
					jsonObject.put("isBind", false);
				}
				//第一次登录
			} else {
				user = new User();
				user.setOpenId(openId);

				user.setNickname(userInfo.getNickname());
				user.setHeadPhoto(userInfo.getHeadPhoto());
				user.preInsert();
				baseMapper.insert(user);
				jsonObject.put("isBind", false);
			}
			//给用户jwt加密生成token
			String token = JWT.sign(user, 60L * 30L * 1000L);


			//封装成对象返回给客户端
			jsonObject.put("token", token);
			jsonObject.put("user", user);
			result.setData(jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
			result = TableResult.ErrorResult("认证失败");
		}
		return result;
	}

	@Override
	public Page<User> findUserMessageList(Page<User> page, User user) {





		return null;
	}
	@Override
	public String getOpenIdByUserId(Integer userId){
		User query = new User();
		query.setId(userId);
		User user = baseMapper.selectOne(query);

		return user==null?null:user.getOpenId();
	}
}
